package genedit.controller.interfaceActions;

import genedit.gui.GFileChooser;
import genedit.gui.GMainFrame;
import genedit.gui.GProjectTree;
import genedit.model.HierarchyElement;
import genedit.model.Project;
import genedit.model.Workspace;
import genedit.model.graph.GraphDocument;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.tree.TreeNode;

/**
 * Akcija za čuvanje projekta na izabranu lokaciju u izabranom formatu.
 * 
 * @author Nikola
 * @version 1.2 10/1/14
 */
public class GSaveAsA extends AbstractAction {
	private static final long serialVersionUID = 1L;

	private static GSaveAsA instance = null;

	public static GSaveAsA getInstance() {
		if (instance == null)
			instance = new GSaveAsA();
		return instance;
	}

	public GSaveAsA() {
		putValue(NAME, "Save As");
		putValue(SMALL_ICON, new ImageIcon("resources/icons/floppy_disk.png"));
		putValue(MNEMONIC_KEY, KeyEvent.VK_A);
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
		putValue(SHORT_DESCRIPTION, "Save As");
	}

	/**
	 * Akcija poziva prozor u kom korisnik bira lokaciju i format čuvanja
	 * projekta. Ukoliko korisnik potvrdi sačuvavanje na datoj lokaciji se
	 * kreira datoteka u datom formatu.
	 */
	public void actionPerformed(ActionEvent arg0) {
		GraphDocument document = null;
		TreeNode element = null;
		if (GProjectTree.getInstance().getTree().hasFocus()) {
			element = (TreeNode) GProjectTree.getInstance().getTree()
					.getLastSelectedPathComponent();
			if (element instanceof GraphDocument) {
				GMainFrame.getInstance().documentSaved(document);
				document = (GraphDocument) element;
			}
		} else if (Workspace.getInstance().getActiveDocument() != null) {
			document = Workspace.getInstance().getActiveDocument().getModel();
			GMainFrame.getInstance().documentSaved(document);
			element = (TreeNode) document;
		} else {
			return;
		}

		if (element instanceof Workspace)
			return;

		while (!(element instanceof Project))
			element = (HierarchyElement) element.getParent();

		if (GFileChooser.getInstance(false).showSaveDialog(GMainFrame.getInstance()) == JFileChooser.APPROVE_OPTION) {
			File fileName = null;
			int i = -1;
			if ((i = GFileChooser.getInstance(false).getSelectedFile().toString().indexOf(".proj")) > 0) {
				fileName = new File(GFileChooser.getInstance(false).getSelectedFile().toString()
						.substring(0, i + 5));
			} else if ((i = GFileChooser.getInstance(false).getSelectedFile().toString()
					.indexOf(".xml")) > 0) {
				fileName = new File(GFileChooser.getInstance(false).getSelectedFile().toString()
						.substring(0, i + 4));
			} else {
				if (GFileChooser.getInstance(false).getFileFilter().getDescription()
						.contains("XML"))
					fileName = new File(GFileChooser.getInstance(false).getSelectedFile() + ".xml");
				else
					fileName = new File(GFileChooser.getInstance(false).getSelectedFile() + ".proj");
			}

			if (fileName.exists()) {
				if (JOptionPane.showConfirmDialog(null, "Replace existing file?", "Overwrite file",
						JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
					if (document != null) {
						GMainFrame.getInstance().documentChanged(document);
					}
					return;
				}
			}

			Project project = (Project) element;

			// Kada se postavi putanja gde da se sacuva dokument, imenuj ga tako
			String[] tempName = fileName.toString().split("\\\\");
			String temp = tempName[tempName.length - 1];
			if (temp.contains(".xml")) {
				project.rename(temp.substring(0, temp.length() - 4));
			} else {
				project.rename(temp.substring(0, temp.length() - 5));
			}

			try {
				project.setPath(fileName.getCanonicalPath());
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			try {
				if (fileName.getCanonicalPath().contains(".xml")) {
					BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
							new FileOutputStream(fileName), "UTF8"));
					Workspace.getInstance().getXstream().toXML(project, out);
				} else {
					ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
							fileName.getCanonicalPath()));
					out.writeObject(project);
					out.close();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			File workspacePath=Workspace.getInstance().getPath();
			GFileChooser.getInstance(false).setCurrentDirectory(workspacePath);
		} else {
			if (document != null) {
				GMainFrame.getInstance().documentChanged(document);
			}
		}
	}

}